package com.wxmit.module.system.web;


import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.core.util.IdUtil;
import com.wxmit.base.constant.ShushanConstants;
import com.wxmit.framework.satoken.core.annotation.Anonymous;
import com.wxmit.starter.cache.api.CacheApi;
import com.wxmit.starter.cache.domain.CacheTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
@Slf4j
public class CaptchaController
{
    @Autowired
    private CacheApi cacheApi;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    @Anonymous
    public Map getCode(HttpServletResponse response) throws IOException
    {
        // 生成随机字串
        // 生成图片
        int w = 111;
        int h = 36;
        int interfere = 5;
        int codeCount = 4;
        AbstractCaptcha captcha = CaptchaUtil.createLineCaptcha(w, h,codeCount,interfere);


        String verifyCode = captcha.getCode();
        // 唯一标识
        String uuid = IdUtil.simpleUUID();
        String verifyKey = ShushanConstants.CAPTCHA_CODE_KEY + uuid;

        cacheApi.setString(verifyKey, verifyCode);
        cacheApi.expire(verifyKey,new CacheTime(ShushanConstants.CAPTCHA_EXPIRATION,TimeUnit.MINUTES));
        Map<String,Object> imgMap =  new HashMap<>(2);
        imgMap.put("uuid", uuid);
        imgMap.put("img", captcha.getImageBase64());
        return imgMap;

    }
}
